Strange ruby behavior when using Hash.new([])

Posted by Valentin Vasilyev on Stack Overflow See other posts from Stack Overflow or by Valentin Vasilyev
Published on 2010-04-23T12:32:45Z Indexed on 2010/04/23 12:33 UTC
Read the original article Hit count: 335

Filed under:
|

Consider this code:

h=Hash.new(0) #new hash pairs will by default have 0 as values
h[1]+=1 # {1=>1}
h[2]+=2 # {2=>2}

that's all fine, but:

h=Hash.new([]) #empty array as default value
h[1]<<=1 #{1=>[1]} - OK
h[2]<<=2 #{1=>[1,2], 2=>[1,2]} # why ?? 

At this point I expect the hash to be:

{1=>[1], 2=>[2]}

But something goes wrong.

Does anybody know what happens?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about hash